package com.jiangjiang.eshop.comment.schedule;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jiangjiang.eshop.comment.biz.CommentInfoBiz;
import com.jiangjiang.eshop.comment.dto.CommentInfoDTO;
import com.jiangjiang.eshop.comment.service.CommentAggregateService;
import com.jiangjiang.eshop.order.dto.OrderInfoDTO;
import com.jiangjiang.eshop.order.dto.OrderItemDTO;
import com.jiangjiang.eshop.order.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @ClassName AutoPublishCommentTask
 * @Description TODO
 * @Author jhw
 * @Date 2021/5/31 21:03
 * @Version 1.0
 **/
@Slf4j
@Component
public class AutoPublishCommentTask {
    @Autowired
    private OrderService orderService;

    @Autowired
    private CommentInfoBiz commentInfoBiz;

    @Autowired
    private CommentAggregateService commentAggregateService;

    @Scheduled(fixedRate = 10 * 60 * 1000)
    public void execute(){
        try {
            // 获取确认收获时间超过7天，而且还没有发表评论的订单
            List<OrderInfoDTO> orderInfoDTOS = orderService.listNotPublishedCommentOrders();
            if(CollectionUtils.isEmpty(orderInfoDTOS)){
                return;
            }

            List<Long> orderInfoIds = new ArrayList<>(orderInfoDTOS.size());
            for (OrderInfoDTO orderInfoDTO : orderInfoDTOS) {
                if(CollectionUtils.isEmpty(orderInfoDTO.getOrderItems())){
                    continue;
                }

                orderInfoIds.add(orderInfoDTO.getId());

                for (OrderItemDTO orderItem : orderInfoDTO.getOrderItems()) {
                    // 根据下单的商品条明细自动发表评论
                    CommentInfoDTO commentInfoDTO = commentInfoBiz.saveAutoPublishCommentInfo(orderInfoDTO, orderItem);
                    // 更新评论聚合数据
                    commentAggregateService.saveOrUpdate(commentInfoDTO);
                }

            }

            // 通知订单批量发表了评论
            orderService.informBatchPublishCommentEvent(orderInfoIds);

        } catch (Exception e){
            log.warn("error",e);
        }
    }
}
